package com.udf.service.impl;

import com.udf.bean.CheckRoot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.oxm.Unmarshaller;
import org.springframework.stereotype.Service;

import javax.xml.transform.stream.StreamSource;

/**
 * Created by 张未然 on 2015/9/2.
 */
public class BeanReadService implements com.udf.service.IBeanReadService {

    private Resource location;

    @Autowired
    private Unmarshaller unmarshaller;

    private boolean onLive = false;

    private CheckRoot checkRoot;

    private static Logger log = LoggerFactory.getLogger(BeanReadService.class);

    public Resource getLocation() {
        return location;
    }

    public void setLocation(Resource location) {
        this.location = location;
    }

    public void setOnLive(boolean onLive) {
        this.onLive = onLive;
    }

    private CheckRoot loadCheckBean() {
        try {
            checkRoot = (CheckRoot) unmarshaller.unmarshal(new StreamSource(location.getInputStream()));
        } catch (Exception e) {
            log.error("读取检测配置文件出错:{}，请检查！",e.getMessage());
            e.printStackTrace();
        }
        log.debug("成功载入检测配置文件");
        return checkRoot;
    }

    public CheckRoot getCheckBean(){
        if(onLive){
            loadCheckBean();
            return checkRoot;
        }else{
            if(checkRoot==null){
                //初始化，载入配置文件
                loadCheckBean();
            }
            return checkRoot;
        }
    }
}
